package py.com.alfa.escriba.gui.controller;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.WebApplicationContext;
import org.thymeleaf.TemplateEngine;
import org.winter.dialect.response.JsonResponse;
import org.winter.dialect.response.MsgSeverity;
import org.winter.utils.command.AjaxResponse;
import org.winter.utils.command.ControllerObject;

import py.com.alfa.escriba.gui.controller.object.admin.ControlesControllerObject;
import py.com.alfa.escriba.gui.controller.view.View;
import py.com.alfa.escriba.gui.controller.view.ViewManager;
import py.com.alfa.escriba.gui.dto.GenerateEscrituraDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesDatosDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesEscriturasDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesFormulariosInfoDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesInfoDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesInmueblesInfoDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesNaturalezasDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesNaturalezasInfoDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesPersonasDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesPersonasInfoDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesVehiculosDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesVehiculosInfoDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlesseguimientoDTO;
import py.com.alfa.escriba.gui.dto.admin.ControlestextoDTO;
import py.com.alfa.escriba.gui.dto.admin.DistritoDTO;
import py.com.alfa.escriba.gui.dto.admin.DomicilioDTO;
import py.com.alfa.escriba.gui.dto.admin.NaturalezasDTO;
import py.com.alfa.escriba.gui.dto.admin.PersonaInfoParaControlDTO;
import py.com.alfa.escriba.gui.dto.admin.TabRefDTO;
import py.com.alfa.escriba.gui.dto.admin.UsuarioDTO;
import py.com.alfa.escriba.gui.dto.gestion.InmueblesDTO;
import py.com.alfa.escriba.gui.dto.gestion.VehiculosDTO;
import py.com.alfa.escriba.gui.dto.query.ControlesQueryDTO;
import py.com.alfa.escriba.gui.dto.query.ControlesRequestDTO;
import py.com.alfa.escriba.gui.dto.query.PersonaQueryDTO;
import py.com.alfa.escriba.gui.rest.services.AdminService;
import py.com.alfa.escriba.gui.rest.services.AdministracionService;
import py.com.alfa.escriba.gui.rest.services.ControlesService;
import py.com.alfa.escriba.gui.rest.services.InmueblesService;
import py.com.alfa.escriba.gui.rest.services.ReferenciaService;
import py.com.alfa.escriba.gui.rest.services.TemplatesService;
import py.com.alfa.escriba.gui.rest.services.VehiculosService;
import py.com.alfa.escriba.gui.services.HelperService;
import py.com.alfa.escriba.gui.services.TabRef;
import py.com.alfa.escriba.gui.session.SystemInfo;
import py.com.alfa.escriba.gui.spring.processors.SpringBean;
import py.com.alfa.escriba.gui.utils.DateUtils;
import py.com.alfa.escriba.gui.utils.ObjectUtils;
import py.com.sif.rest.client.spring.exception.RestClientException;

@Controller
@Scope("session")
@SessionAttributes("controles")
@RequestMapping("/controles")
public class ControlesController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3807025844096914070L;
	private final static String PAGE_NAME = "pag:controles";
	private final static String CONTROLLER_OBJECT_NAME = "controles";
	
	private Logger log = LoggerFactory.getLogger(getClass());
	@SpringBean private SystemInfo systemInfo;
	@SpringBean private ViewManager viewManager;
	@SpringBean private HelperService helperService;
	@SpringBean private ControlesService controlesService;
	@SpringBean private ReferenciaService referenciaService;
	@SpringBean private AdminService adminService;
	@SpringBean private VehiculosService vehiculosService;
	@SpringBean private AdministracionService administracionService;
	@SpringBean private InmueblesService inmueblesService;
	@SpringBean private TemplatesService templatesService;
	
	@Autowired
	private WebApplicationContext wac;
	
	@Autowired
	private TemplateEngine templateEngine;
	@ControllerObject	
	private ControlesControllerObject controles;
	private Locale locale;
	
	
	public ControlesController() {
		this.loadObjects();
	}

	private void loadObjects() {
		setLocale(LocaleContextHolder.getLocale());
	}

	private String verifAuto() {
		Subject subject = SecurityUtils.getSubject();
		if (subject == null || !subject.isAuthenticated()) {
			return "redirect:/";
		}		
		Boolean permitted = subject.isPermitted(ControlesController.PAGE_NAME);
		systemInfo.setSystemError(false);
		if (!permitted) {
			systemInfo.setSystemError(true);
			systemInfo.setErrorMessage("El usuario no esta autorizado para utilizar este recurso");
			return "error";
		}
		return null;
	}

	@ModelAttribute(CONTROLLER_OBJECT_NAME)
	public ControlesControllerObject getControles() {
		return this.controles;
	}

	public void setControles(ControlesControllerObject listas) {
		this.controles = listas;
	}

	public Locale getLocale() {
		return locale;
	}

	public void setLocale(Locale locale) {
		this.locale = locale;
	}
	
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String homePage(Model model, HttpServletRequest request, HttpServletResponse response) {
		this.log.info("controles!");
		try {
			this.getControles().view().disableAll();
			String auto = this.verifAuto();
			if ( auto != null ) {
				return auto;
			}
			
			this.getControles().setFiltros(new ControlesQueryDTO());
			if(systemInfo.getEscribano() != null){
				this.getControles().getFiltros().setEscribano(systemInfo.getEscribano());
			}
			List<TabRefDTO>estadosEscrituras= new ArrayList<TabRefDTO>();
			for (TabRefDTO tr:helperService.getTablaRef(TabRef.ESTADO_ESCRITURA)){
				estadosEscrituras.add(tr);
			}
			TabRefDTO estadoAnulado = helperService.getTablaRef(TabRef.ESTADO_ESCRITURA, "020");
			estadosEscrituras.remove(estadoAnulado);
			this.getControles().setEstadosEscrituras(estadosEscrituras);
			this.getControles().setEstadosControl(this.helperService.getTablaRef(TabRef.ESTADO_CONTROL));
			this.getControles().setTiposNaturaleza(this.referenciaService.listNaturalezas());
			this.getControles().setMonedas(this.helperService.getMonedas());
			this.getControles().setTiposDocumento(this.helperService.getTablaRef(TabRef.TIPO_DOC));
			this.getControles().setRolesEscribano(this.helperService.getTablaRef(TabRef.ROLES_ESCRIBANO));
			this.getControles().setPaises(this.helperService.getPaises());
			this.getControles().setTiposProtocolo(this.helperService.getTablaRef(TabRef.TIPO_PROTOCOLO));
			this.getControles().setTiposFormularios(this.helperService.getFormularios());
			this.getControles().setDepartamentos(this.helperService.getDepartamentos());
			this.getControles().setDistritos(new ArrayList<DistritoDTO>());
			this.getControles().setControles(null);
			
			this.getControles().view().enable().lista();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return View.CONTROLES;
	}
	
	@RequestMapping(value = "/buscarControles", method = RequestMethod.POST)
	public @ResponseBody JsonResponse buscarControles(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("\n============== CONSULTAR CONTROLES! {}\n==============\n");
		try {
			if(this.getControles().getFiltros().getFechaDesde() != null ||
					this.getControles().getFiltros().getFechaHasta() != null){
				Date fechaDesde = DateUtils.getDateWFirstHms(getControles().getFiltros().getFechaDesde().getTime());
				Date fechaHasta = DateUtils.getDateWLastHms(getControles().getFiltros().getFechaHasta().getTime());

				if (!DateUtils.daysBetweenDates(fechaDesde, fechaHasta, 30))
					throw new Exception("El rango de fechas maximo es que 30 dias");

				if (DateUtils.isBefore(fechaHasta, fechaDesde))
					throw new Exception("Rango de fechas invalido");

				if (DateUtils.isAfterToday(DateUtils.getDateWFirstHms(fechaHasta.getTime())))
					throw new Exception("Rango de fechas no puede superar al dia actual");
				  
				this.getControles().getFiltros().setFechaDesde(fechaDesde);
				this.getControles().getFiltros().setFechaHasta(fechaHasta);
			}
			
			this.getControles().setControles(this.controlesService.listControlesRequest(this.getControles().getFiltros()));
			this.log.info("CONTROLES: {}", this.getControles().getControles());
			this.getControles().view().disableAll().enable().lista();
		} catch (Exception e) {
			this.getControles().setControles(new ArrayList<ControlesRequestDTO>());
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	@RequestMapping(value = "/agregarControl", method = RequestMethod.POST)
	public @ResponseBody JsonResponse agregarControl(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROLES) JsonResponse jResponse) {
		this.log.info("controles - Nuevo!");
		try {
			
			this.getControles().setControl(new ControlesInfoDTO());
			this.getControles().getControl().setEstado(this.helperService.getTablaRef("ESTCONTROL", new Long(36)));
			
			this.getControles().view().disableAll().enable().control();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}	

	@RequestMapping(value = "/editarControl/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarControl(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR CONTROL! {}\n==============\n", ind);
		try {
			
			Integer index = Integer.parseInt(ind);
			ControlesRequestDTO obj = this.getControles().getControles().get(index);
			
			this.log.info("CONTROL: {}", obj);
			ControlesInfoDTO dto = this.controlesService.showControl(obj.getIdControl());
			
			this.getControles().setControl(dto);
			this.getControles().view().disableAll().enable().control();
			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	@RequestMapping(value = "/eliminarControl/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarControl(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== BORRAR CONTROL! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesRequestDTO obj = this.getControles().getControles().get(index);
			this.log.info("CONTROL: {}", obj);
			this.controlesService.deleteControl(obj.getIdControl());
			this.getControles().setControles(this.controlesService.listControlesRequest(this.getControles().getFiltros()));
			this.getControles().view().disableAll().enable().lista();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/guardarControl", method = RequestMethod.POST)
  public @ResponseBody JsonResponse guardarControl(Model model, HttpServletRequest request,
      HttpServletResponse response, @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
  
	  this.log.info("\n==============\nGUARDANDO CONTROL! \n==============\n");
		try {
			
			ControlesInfoDTO obj = this.getControles().getControl();
			
			if(CollectionUtils.isEmpty(obj.getPersonas())){
				return jResponse.error("Debe informar por lo menos una persona");
			}
			
			if(CollectionUtils.isEmpty(obj.getNaturalezas())){
				return jResponse.error("Debe informar por lo menos una naturaleza");
			}
			
			if ( obj.getId() == null ) {
				obj.setIdescribano(systemInfo.getIdEscribano());
				obj.setIdusuario(systemInfo.getIdUser());
				this.log.info("Control: {}", obj);
				this.controlesService.createControl(obj);
			} else {
				if ( this.getControles().getControl().getAgregar() == null) {
					this.getControles().getControl().setAgregar(new ControlesDatosDTO());
				}
				if ( this.getControles().getControl().getEliminar() == null) {
					this.getControles().getControl().setEliminar(new ControlesDatosDTO());
				}
				
				this.log.info("Control: {}", obj);
				this.controlesService.saveControl(obj);
			}
			this.getControles().setFiltros(new ControlesQueryDTO());
			if(systemInfo.getEscribano() != null){
				this.getControles().getFiltros().setEscribano(systemInfo.getEscribano());
			}
			this.getControles().setControles(this.controlesService.listControlesRequest(this.getControles().getFiltros()));
			this.getControles().view().disableAll().enable().lista();
			jResponse.setView(View.CONTROLES);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		
		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	@RequestMapping(value = "/cancelar/{operacion}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse cancelar(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		@PathVariable("operacion") String operacion) {
		this.log.info("controles - cancelar! {}", operacion);
		try {
			if ( operacion == null ) {
				return jResponse.error("Debe informar la operacion a cancelar");
			} else if ( "CONTROL".equals(operacion)) {
			    this.getControles().setControl(null);
			    this.getControles().view().disableAll().enable().lista();
			    jResponse.setView(View.CONTROLES);
			}else if ( "NATURALEZA".equals(operacion)) {
		        this.getControles().setNaturaleza(null);
		        this.getControles().view().disableAll().enable().control();
		        jResponse.setView(View.CONTROL_NATURALEZA);
			}else if ( "PERSONA".equals(operacion)) {
		        this.getControles().setPersona(null);
		        this.getControles().view().disableAll().enable().control();
		        jResponse.setView(View.CONTROL_PERSONA);
			}else if ( "VEHICULO".equals(operacion)) {
		        this.getControles().setVehiculo(null);
		        this.getControles().view().disableAll().enable().control();
		        jResponse.setView(View.CONTROL_VEHICULO);
			} else if ( "INMUEBLE".equals(operacion)) {
			    this.getControles().setInmueble(null);
			    this.getControles().view().disableAll().enable().inmueble();
			    jResponse.setView(View.CONTROL_INMUEBLE);
			} else if ( "FORMULARIO".equals(operacion)) {
			    this.getControles().setFormulario(null);
			    this.getControles().view().disableAll().enable().formulario();
			    jResponse.setView(View.CONTROL_FORMULARIO);
			} else if ( "FORMULARIOS".equals(operacion)) {
				this.getControles().setControl(null);
			    this.getControles().setFormulario(null);
			    this.getControles().view().disableAll().enable().lista();
				jResponse.setView(View.CONTROLES);
			} else if ( "NOTAS".equals(operacion)) {
				this.getControles().setControl(null);
			    this.getControles().setNota(null);
			    this.getControles().setNotas(null);
			    this.getControles().view().disableAll().enable().lista();
			    jResponse.setView(View.CONTROLES);
			} else if ( "NOTA".equals(operacion)) {
				this.getControles().setNota(null);
			    this.getControles().view().disableAll().enable().notas();
			    jResponse.setView(View.CONTROL_NOTA);
			}else if ( "ESCRITURAS".equals(operacion)) {
				this.getControles().setControl(null);
			    this.getControles().setControlEscritura(null);
			    this.getControles().setOrdenCronologico(null);
			    this.getControles().view().disableAll().enable().lista();
			    jResponse.setView(View.CONTROLES);
			}else if ( "TEXTOS".equals(operacion)) {
				this.getControles().setControl(null);
			    this.getControles().setTexto(null);
			    this.getControles().view().disableAll().enable().lista();
			    jResponse.setView(View.CONTROLES);
			}
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/agregarNaturaleza", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addNaturaleza(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("controles - Agregar Naturaleza!");
		try {
			this.getControles().setNaturaleza(new ControlesNaturalezasInfoDTO());
			this.getControles().getNaturaleza().setMoneda(this.helperService.getMonedasByCodigo("DOL"));
			this.getControles().view().disableAll().enable().control().naturaleza();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}	

	@RequestMapping(value = "/eliminarNaturaleza/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarNaturaleza(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO NATURALEZA! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesNaturalezasInfoDTO dto = obj.getNaturalezas().get(index);
			if( dto == null) {
				return jResponse.error("No existe la naturaleza en la lista");
			}
			if ( obj.getEliminar() == null) {
				obj.setEliminar(new ControlesDatosDTO());
			}
			if ( obj.getEliminar().getNaturalezas() == null) {
				obj.getEliminar().setNaturalezas(new ArrayList<ControlesNaturalezasInfoDTO>());
			}
			if ( obj.getModificar() != null && obj.getModificar().getNaturalezas() != null) {
				obj.getModificar().getNaturalezas().remove(dto);
			}
			if ( obj.getAgregar() != null && obj.getAgregar().getNaturalezas() != null) {
				obj.getAgregar().getNaturalezas().remove(dto);
			}			
			if ( dto.getId() != null ) {
				obj.getEliminar().getNaturalezas().add(dto);
			}
			
			obj.getNaturalezas().remove(dto);
			this.getControles().view().disableAll().enable().control();
			jResponse.setView(View.CONTROL_NATURALEZA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	

	@RequestMapping(value = "/editarNaturaleza/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarNaturaleza(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR NATURALEZA! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesNaturalezasInfoDTO dto = obj.getNaturalezas().get(index);
			if( dto == null) {
				return jResponse.error("No existe el naturaleza en la lista");
			}
			dto.setNaturaleza(this.referenciaService.showNaturalezas(dto.getIdnaturaleza()));
			this.log.info("NATURALEZA: {}", dto);
			this.getControles().setNaturaleza(dto);
			this.getControles().view().enable().control().naturaleza();
//			jResponse.setView(View.CONTROL_NATURALEZA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/grabarNaturaleza", method = RequestMethod.POST)
	public @ResponseBody JsonResponse grabarNaturaleza(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("GUARDAR NATURALEZA!");
		try {
			
			if ( this.getControles().getControl().getModificar() == null) {
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getModificar().getNaturalezas() == null ) {
				this.getControles().getControl().getModificar().setNaturalezas(new ArrayList<ControlesNaturalezasInfoDTO>());
			}
			
			if ( this.getControles().getControl().getAgregar() == null) {
				this.getControles().getControl().setAgregar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getAgregar().getNaturalezas() == null ) {
				this.getControles().getControl().getAgregar().setNaturalezas(new ArrayList<ControlesNaturalezasInfoDTO>());
			}
			if ( this.getControles().getControl().getNaturalezas() == null) {
				this.getControles().getControl().setNaturalezas(new ArrayList<ControlesNaturalezasInfoDTO>());
			}
			
			Integer index = this.getControles().getControl().getNaturalezas().indexOf(this.getControles().getNaturaleza());

			if ( this.getControles().getNaturaleza().getId() == null && index < 0) {
				if( !this.getControles().getControl().getAgregar().getNaturalezas().contains(this.getControles().getNaturaleza()) ) {
					ControlesNaturalezasInfoDTO naturaleza = new ControlesNaturalezasInfoDTO();
					ObjectUtils.copyValues(this.getControles().getNaturaleza(), naturaleza);
					naturaleza.setOrden(this.getControles().getControl().getNaturalezas().size()+1);
					this.log.info("AGREGO NATURALEZA! : {}", naturaleza);
					this.getControles().getControl().getAgregar().getNaturalezas().add(naturaleza);
					this.getControles().getControl().getNaturalezas().add(naturaleza);
				}
			} else if(index >= 0) {
				ControlesNaturalezasInfoDTO naturaleza = this.getControles().getControl().getNaturalezas().get(index);
				this.log.info("MODIFICO NATURALEZA! : {}", this.getControles().getNaturaleza());
				this.getControles().getNaturaleza().setOrden(index+1);
				ObjectUtils.copyValues(this.getControles().getNaturaleza(), naturaleza);
				this.log.info("MODIFICO NATURALEZA! : {}", naturaleza);

				Integer indMod = this.getControles().getControl().getModificar().getNaturalezas().indexOf(this.getControles().getNaturaleza());
				if( indMod < 0 ) {
					this.getControles().getControl().getModificar().getNaturalezas().add(naturaleza);
				}else{
					ControlesNaturalezasInfoDTO vehMod = this.getControles().getControl().getModificar().getNaturalezas().get(indMod);
					this.getControles().getNaturaleza().setOrden(index+1);
					ObjectUtils.copyValues(this.getControles().getNaturaleza(), vehMod);
				}
			}
			
			this.getControles().setNaturaleza(null);
			this.getControles().view().disableAll().enable().control();
			this.log.info("FIN!");
//			jResponse.setView(View.CONTROL_NATURALEZA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			} else {
				return jResponse.error(e.getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }
	
	@RequestMapping(value = "/acNaturaleza", method = RequestMethod.GET)
	public @ResponseBody List<NaturalezasDTO> acNaturaleza(@RequestParam("term") String name) {
	  this.log.info("AutoComplete Naturaleza!  ============ {}", name);
	  List<NaturalezasDTO> lista = new ArrayList<NaturalezasDTO>();
	  
	  if ( this.getControles().getTiposNaturaleza() == null) {
	    return lista;
	  }
	  if ( name == null) {
	    return this.getControles().getTiposNaturaleza();
	  }
	  
	  for (NaturalezasDTO dto : this.getControles().getTiposNaturaleza()) {
	    if ( dto.getNombre().toUpperCase().startsWith(name.toUpperCase())){
	      lista.add(dto);
	    }
	  }
	  return lista;  
	}
	
	@RequestMapping(value = "/eventNaturaleza", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eventNaturaleza(Model model, HttpServletRequest request, HttpServletResponse response, 
	    @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
	  
	  this.log.info("controles - Event Naturaleza!");
	  try {
	    if(this.getControles().getNaturaleza().getIdnaturaleza() != null){
	      NaturalezasDTO dto = this.referenciaService.showNaturalezas(this.getControles().getNaturaleza().getIdnaturaleza());
	      this.getControles().getNaturaleza().setNaturaleza(dto);
	    }else{
	      this.getControles().getNaturaleza().setNaturaleza(new NaturalezasDTO());
	    }
	    jResponse.setView(View.CONTROL_NATURALEZA);
	  } catch (Exception e) {
	    this.log.error(e.getMessage(), e);
	    if (e.getCause() != null && e.getCause() instanceof RestClientException) {
	      return jResponse.error(e.getCause().getMessage());
	    }
	  }
	  return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/agregarPersona", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addPersona(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("controles - Agregar Persona!");
		try {
			ControlesPersonasInfoDTO dto = new ControlesPersonasInfoDTO();
			dto.setTipoDocumento(this.helperService.getTablaRef(TabRef.TIPO_DOC, 9L));
			System.out.println("TiposDocumentos:"+this.getControles().getTiposDocumento());
			this.getControles().setRuc(true);
			dto.setPais(this.helperService.getPaisByCodigo("PRY"));
			
			this.getControles().setPersona(dto);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		this.getControles().view().disableAll().enable().control().persona();
		return jResponse.success(request, response, wac, model, templateEngine);
	}	

	@RequestMapping(value = "/eliminarPersona/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarPersona(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO PERSONA! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesPersonasInfoDTO dto = obj.getPersonas().get(index);
			if( dto == null) {
				return jResponse.error("No existe la persona en la lista");
			}
			if ( obj.getEliminar() == null) {
				obj.setEliminar(new ControlesDatosDTO());
			}
			if ( obj.getEliminar().getPersonas() == null) {
				obj.getEliminar().setPersonas(new ArrayList<ControlesPersonasInfoDTO>());
			}
			if ( obj.getModificar() != null && obj.getModificar().getPersonas() != null) {
				obj.getModificar().getPersonas().remove(dto);
			}
			if ( obj.getAgregar() != null && obj.getAgregar().getPersonas() != null) {
				obj.getAgregar().getPersonas().remove(dto);
			}			
			if ( dto.getId() != null ) {
				obj.getEliminar().getPersonas().add(dto);
			}
			
			obj.getPersonas().remove(index.intValue());
			this.getControles().view().disableAll().enable().control();
			jResponse.setView(View.CONTROL_PERSONA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	

	@RequestMapping(value = "/editarPersona/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarPersona(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR PERSONA! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesPersonasInfoDTO dto = obj.getPersonas().get(index);
			if( dto == null) {
				return jResponse.error("No existe el persona en la lista");
			}
//			dto.setPersona(this.adminService.obtenerPersona(dto.getIdpersona()));
			
			if(ObjectUtils.isNotEmpty(dto.getIdtipodocumento())){
				TabRefDTO tipodoc = this.helperService.getTablaRef(TabRef.TIPO_DOC, dto.getIdtipodocumento());
				dto.setTipoDocumento(tipodoc);
				this.getControles().setRuc("RUC".equals(tipodoc.getCodigo()));
			}
			this.log.info("PERSONA: {}", dto);
			this.log.info("PERSONAID: {}", dto.getIdpersona());
			this.getControles().setPersona(dto);
			this.getControles().view().disableAll().enable().control().persona();
//			jResponse.setView(View.CONTROL_PERSONA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/grabarPersona", method = RequestMethod.POST)
	public @ResponseBody JsonResponse grabarPersona(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("GUARDAR PERSONA!");
		try {
			
			if ( this.getControles().getControl().getModificar() == null) {
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getModificar().getPersonas() == null ) {
				this.getControles().getControl().getModificar().setPersonas(new ArrayList<ControlesPersonasInfoDTO>());
			}
			
			if ( this.getControles().getControl().getAgregar() == null) {
				this.getControles().getControl().setAgregar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getAgregar().getPersonas() == null ) {
				this.getControles().getControl().getAgregar().setPersonas(new ArrayList<ControlesPersonasInfoDTO>());
			}
			if ( this.getControles().getControl().getPersonas() == null) {
				this.getControles().getControl().setPersonas(new ArrayList<ControlesPersonasInfoDTO>());
			}
			
			/*boolean continueControl = (this.getControles().getControl().getPersonas() == null ? true : 
				!this.getControles().getControl().getPersonas().contains(this.getControles().getPersona()) ? true:false);
			
			if ( this.getControles().getPersona().getId() == null && continueControl) {
				if( !this.getControles().getControl().getAgregar().getPersonas().contains(this.getControles().getPersona()) ) {
					ControlesPersonasInfoDTO persona = new ControlesPersonasInfoDTO();
					ObjectUtils.copyValues(this.getControles().getPersona(), persona);
					persona.setOrden(this.getControles().getControl().getPersonas().size()+1);
					this.log.info("AGREGO PERSONA! : {}", persona);
				  this.getControles().getControl().getAgregar().getPersonas().add(persona);
				  this.getControles().getControl().getPersonas().add(persona);
				}
			} else if(continueControl) {
				if( !this.getControles().getControl().getModificar().getPersonas().contains(this.getControles().getPersona()) ) {
				  ControlesPersonasInfoDTO persona = new ControlesPersonasInfoDTO();
		          ObjectUtils.copyValues(this.getControles().getPersona(), persona);
		          this.log.info("MODIFICO PERSONA! : {}", persona);
				  this.getControles().getControl().getModificar().getPersonas().add(persona);
				}			
			}*/
			
			Integer index = this.getControles().getControl().getPersonas().indexOf(this.getControles().getPersona());

			if ( this.getControles().getPersona().getId() == null && index < 0) {
				if( !this.getControles().getControl().getAgregar().getPersonas().contains(this.getControles().getPersona()) ) {
					ControlesPersonasInfoDTO persona = new ControlesPersonasInfoDTO();
					ObjectUtils.copyValues(this.getControles().getPersona(), persona);
					persona.setOrden(this.getControles().getControl().getPersonas().size()+1);
					this.log.info("AGREGO PERSONA! : {}", persona);
					this.getControles().getControl().getAgregar().getPersonas().add(persona);
					this.getControles().getControl().getPersonas().add(persona);
				}
			} else if(index >= 0) {
				ControlesPersonasInfoDTO persona = this.getControles().getControl().getPersonas().get(index);
				this.log.info("MODIFICO PERSONA! : {}", this.getControles().getPersona());
				this.getControles().getPersona().setOrden(index+1);
				ObjectUtils.copyValues(this.getControles().getPersona(), persona);
				this.log.info("MODIFICO PERSONA! : {}", persona);

				Integer indMod = this.getControles().getControl().getModificar().getPersonas().indexOf(this.getControles().getPersona());
				if( indMod < 0 ) {
					this.getControles().getControl().getModificar().getPersonas().add(persona);
				}else{
					ControlesPersonasInfoDTO vehMod = this.getControles().getControl().getModificar().getPersonas().get(indMod);
					this.getControles().getPersona().setOrden(index+1);
					ObjectUtils.copyValues(this.getControles().getPersona(), vehMod);
				}
			}
			
			this.getControles().setPersona(null);
			this.getControles().view().disableAll().enable().control();
			this.log.info("FIN!");
//			jResponse.setView(View.CONTROL_PERSONA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			} else {
				return jResponse.error(e.getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }
	
	@RequestMapping(value = "/tipoDocumentoEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse tipoDocumentoEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	       @AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		
		this.log.info("INDICADOR TIPO DOCUMENTO EVENT! {}", this.getControles().getPersona().getTipoDocumento());
		try {
			TabRefDTO tipodoc = this.helperService.getTablaRef(TabRef.TIPO_DOC, this.getControles().getPersona().getIdtipodocumento());
			this.getControles().getPersona().setTipoDocumento(tipodoc);
			this.getControles().setRuc("RUC".equals(tipodoc.getCodigo()));
			jResponse.setView(View.CONTROL_PERSONA_DIALOG);
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	 }
	
	@RequestMapping(value = "/buscarPersona", method = RequestMethod.POST)
	public @ResponseBody JsonResponse buscarPersona(Model model, HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		try {
			PersonaQueryDTO query = new PersonaQueryDTO();
			query.setIdEscribano(systemInfo.getIdEscribano());
			query.setIdPais(this.getControles().getPersona().getIdpais());
			query.setIdTipoDocumento(this.getControles().getPersona().getIdtipodocumento());
			query.setNroDocumento(ObjectUtils.parseString(this.getControles().getPersona().getNrodocumento()));
			query.setDvDocumento(ObjectUtils.parseString(this.getControles().getPersona().getDvdocumento()));
			this.log.info("PERSONA QUERY ! : {}", query);
			PersonaInfoParaControlDTO persona = this.adminService.getPersonaByPaisDocumento(query);
			this.log.info("PERSONA ! : {}", persona);
			
			if(persona == null)
				return jResponse.error("No se encuentra a la persona");
			
			this.getControles().getPersona().setPersona(persona);
			jResponse.setView(View.CONTROL_PERSONA_DIALOG);
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/checkDomicilio/{id}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse checkDomicilio(Model model, HttpServletRequest request, HttpServletResponse response, 
		   @PathVariable("id") String id, @AjaxResponse(View.CONTROLES) JsonResponse jResponse, 
	       @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		
		this.log.info("ID DOMICILIO EVENT! {}", id);
		try {
			Long idDom = Long.parseLong(id);
			for (DomicilioDTO dom : this.getControles().getPersona().getPersona().getDomicilios()) {
				if(idDom.equals(dom.getId())){
					dom.setMarcar(true);
					this.getControles().getPersona().setIddomicilio(dom.getId());
					this.getControles().getPersona().setCalleprincipal(dom.getCallePrincipal());
					this.getControles().getPersona().setNumero(dom.getNumero());
					this.getControles().getPersona().setPiso(dom.getPiso());
					this.getControles().getPersona().setUnidad(dom.getUnidad());
					this.getControles().getPersona().setCallealternativa(dom.getCalleAlternativa());
					this.getControles().getPersona().setIddepartamento(dom.getDepartamento().getId());
					this.getControles().getPersona().setIddistrito(dom.getDistrito().getId());
					this.getControles().getPersona().setDomicilio(dom);
				}else{
					dom.setMarcar(false);
				}
			}
			jResponse.setView(View.CONTROL_PERSONA_DIALOG);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	 }
	
	
	@RequestMapping(value = "/agregarVehiculo", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addVehiculo(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("controles - Agregar Vehiculo!");
		this.getControles().setVehiculo(null);
		this.getControles().setVehiculoBuscar(null);
		this.getControles().view().disableAll().enable().control().vehiculo();
		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	
	@RequestMapping(value = "/eliminarVehiculo/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarVehiculo(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO VEHICULO! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesVehiculosInfoDTO dto = obj.getVehiculos().get(index);
			if( dto == null) {
				return jResponse.error("No existe la Vehiculo en la lista");
			}
			if ( obj.getEliminar() == null) {
				obj.setEliminar(new ControlesDatosDTO());
			}
			if ( obj.getEliminar().getVehiculos() == null) {
				obj.getEliminar().setVehiculos(new ArrayList<ControlesVehiculosInfoDTO>());
			}
			if ( obj.getModificar() != null && obj.getModificar().getVehiculos() != null) {
				obj.getModificar().getVehiculos().remove(dto);
			}
			if ( obj.getAgregar() != null && obj.getAgregar().getVehiculos() != null) {
				obj.getAgregar().getVehiculos().remove(dto);
			}			
			if ( dto.getId() != null ) {
				obj.getEliminar().getVehiculos().add(dto);
			}
			
			obj.getVehiculos().remove(dto);
			this.getControles().view().disableAll().enable().control();
			jResponse.setView(View.CONTROL_VEHICULO);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	

	@RequestMapping(value = "/editarVehiculo/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarVehiculo(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR VEHICULO! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesVehiculosInfoDTO dto = obj.getVehiculos().get(index);
			if( dto == null) {
				return jResponse.error("No existe el Vehiculo en la lista");
			}
			//dto.setVehiculo(this.referenciaService.showNaturalezas(dto.getIdnaturaleza()));
			
			this.log.info("Vehiculo: {}", dto);
			VehiculosDTO vehiculoBuscar= this.vehiculosService.showVehiculo(dto.getIdvehiculo());
			this.getControles().setVehiculoBuscar(vehiculoBuscar);
			this.getControles().setVehiculo(dto);
			this.getControles().view().disableAll().enable().control().vehiculo();
//			jResponse.setView(View.CONTROL_NATURALEZA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/grabarVehiculo", method = RequestMethod.POST)
	public @ResponseBody JsonResponse grabarVehiculo(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("GUARDAR VEHICULO!");
		try {
			if(this.getControles().getVehiculo().getIdvehiculo() == null ) {
				return jResponse.error("No se encuentra el vehiculo");
			}
			
			if ( this.getControles().getControl().getModificar() == null) {
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getModificar().getVehiculos() == null ) {
				this.getControles().getControl().getModificar().setVehiculos(new ArrayList<ControlesVehiculosInfoDTO>());
			}
			
			if ( this.getControles().getControl().getAgregar() == null) {
				this.getControles().getControl().setAgregar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getAgregar().getVehiculos() == null ) {
				this.getControles().getControl().getAgregar().setVehiculos(new ArrayList<ControlesVehiculosInfoDTO>());
			}
			if ( this.getControles().getControl().getVehiculos() == null) {
				this.getControles().getControl().setVehiculos(new ArrayList<ControlesVehiculosInfoDTO>());
			}
			
			Integer index = this.getControles().getControl().getVehiculos().indexOf(this.getControles().getVehiculo());

			if ( this.getControles().getVehiculo().getId() == null && index < 0) {
				if( !this.getControles().getControl().getAgregar().getVehiculos().contains(this.getControles().getVehiculo()) ) {
					ControlesVehiculosInfoDTO vehiculo = new ControlesVehiculosInfoDTO();
					ObjectUtils.copyValues(this.getControles().getVehiculo(), vehiculo);
					vehiculo.setOrden(this.getControles().getControl().getVehiculos().size()+1);
					this.log.info("AGREGO VEHICULO! : {}", vehiculo);
					this.getControles().getControl().getAgregar().getVehiculos().add(vehiculo);
					this.getControles().getControl().getVehiculos().add(vehiculo);
				}
			} else if(index >= 0) {
				ControlesVehiculosInfoDTO vehiculo = this.getControles().getControl().getVehiculos().get(index);
				this.log.info("MODIFICO VEHICULO! : {}", this.getControles().getVehiculo());
				this.getControles().getVehiculo().setOrden(index+1);
				ObjectUtils.copyValues(this.getControles().getVehiculo(), vehiculo);
				this.log.info("MODIFICO VEHICULO! : {}", vehiculo);

				Integer indMod = this.getControles().getControl().getModificar().getVehiculos().indexOf(this.getControles().getVehiculo());
				if( indMod < 0 ) {
					this.getControles().getControl().getModificar().getVehiculos().add(vehiculo);
				}else{
					ControlesVehiculosInfoDTO vehMod = this.getControles().getControl().getModificar().getVehiculos().get(indMod);
					this.getControles().getVehiculo().setOrden(index+1);
					ObjectUtils.copyValues(this.getControles().getVehiculo(), vehMod);
				}
			}
			
			this.getControles().setVehiculo(null);
			this.getControles().view().disableAll().enable().control();
			this.log.info("FIN!");
//			jResponse.setView(View.CONTROL_VEHICULO);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			} else {
				return jResponse.error(e.getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }
	@RequestMapping(value = "/buscarVehiculo", method = RequestMethod.POST)
	public @ResponseBody JsonResponse buscarVehiculo(Model model, HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		try {
			VehiculosDTO buscar = this.getControles().getVehiculoBuscar();
			if(ObjectUtils.isEmpty(buscar.getNrochasis()) && ObjectUtils.isEmpty(buscar.getNroserie())
					&& ObjectUtils.isEmpty(buscar.getChapa())) {
				return jResponse.error("Debe ingresar un parametro para la busqueda");
			}
			
			this.getControles().getVehiculoBuscar().setIdescribano(systemInfo.getIdEscribano());
			List<VehiculosDTO> vehiculos = this.vehiculosService.buscarVehiculos(this.getControles().getVehiculoBuscar());
			this.log.info("vehiculo ! : {}", vehiculos);
			
			VehiculosDTO vehiculo = null;
			if(CollectionUtils.isEmpty(vehiculos)){
				jResponse.setMessage("No se encuentra El Vehiculo", MsgSeverity.ERROR);
			}else{
				vehiculo = vehiculos.get(0);
			}
			
			this.getControles().setVehiculoBuscar(vehiculo);
			this.getControles().getVehiculo().setNrochasis(vehiculo != null ? vehiculo.getNrochasis() : null);
			this.getControles().getVehiculo().setNroserie(vehiculo != null ? vehiculo.getNroserie() : null);
			this.getControles().getVehiculo().setMatricula(vehiculo != null ? vehiculo.getChapa() : null);
			this.getControles().getVehiculo().setIdvehiculo(vehiculo != null ? vehiculo.getId() : null);
			this.getControles().getVehiculo().setVehiculo(vehiculo);
			
			jResponse.setView(View.CONTROL_VEHICULO_DIALOG);
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/controlFormulario/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse controlFormulario(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== FORMULARIO CONTROL! {}\n==============\n", ind);
		try {
			
			Integer index = Integer.parseInt(ind);
			ControlesRequestDTO obj = this.getControles().getControles().get(index);
			
			this.log.info("CONTROL: {}", obj);
			ControlesInfoDTO dto = this.controlesService.showControl(obj.getIdControl());
			dto.setFormularios(this.controlesService.getControlesFormulariosByIdControl(obj.getIdControl()));
			
			this.getControles().setControl(dto);
			this.getControles().view().disableAll().enable().formulario();
			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/agregarFormulario", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addFormulario(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL_FORMULARIO) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("controles - Agregar Formulario!");
		this.getControles().setFormulario(new ControlesFormulariosInfoDTO());
		this.getControles().getFormulario().setFechaRegistro(DateUtils.getCurrentDate());
		this.getControles().getFormulario().setFechaVencimiento(DateUtils.addDays(this.getControles().getFormulario().getFechaRegistro(), 30));
		this.getControles().view().disableAll().enable().formulario();
		return jResponse.success(request, response, wac, model, templateEngine);
	}	

	@RequestMapping(value = "/eliminarFormulario/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarFormulario(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL_FORMULARIO) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO FORMULARIO! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesFormulariosInfoDTO dto = obj.getFormularios().get(index);
			if( dto == null) {
				return jResponse.error("No existe la formulario en la lista");
			}
			if ( obj.getEliminar() == null) {
				obj.setEliminar(new ControlesDatosDTO());
			}
			if ( obj.getEliminar().getFormularios() == null) {
				obj.getEliminar().setFormularios(new ArrayList<ControlesFormulariosInfoDTO>());
			}
			if ( obj.getModificar() != null && obj.getModificar().getFormularios() != null) {
				obj.getModificar().getFormularios().remove(dto);
			}
			if ( obj.getAgregar() != null && obj.getAgregar().getFormularios() != null) {
				obj.getAgregar().getFormularios().remove(dto);
			}			
			if ( dto.getId() != null ) {
				obj.getEliminar().getFormularios().add(dto);
			}
			
			obj.getFormularios().remove(dto);
			this.getControles().view().disableAll().enable().formulario();
			jResponse.setView(View.CONTROL_FORMULARIO);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	

	@RequestMapping(value = "/editarFormulario/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarFormulario(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL_FORMULARIO) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR FORMULARIO! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesFormulariosInfoDTO dto = obj.getFormularios().get(index);
			if( dto == null) {
				return jResponse.error("No existe el formulario en la lista");
			}
			dto = this.controlesService.getControlesFormulariosById(dto.getId());
			this.log.info("FORMULARIO: {}", dto);
			this.getControles().setFormulario(dto);
			this.getControles().view().disableAll().enable().formulario();
//			jResponse.setView(View.CONTROL_FORMULARIO);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/grabarFormulario", method = RequestMethod.POST)
	public @ResponseBody JsonResponse grabarFormulario(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROL_FORMULARIO) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("GUARDAR FORMULARIO!");
		try {
			
			if ( this.getControles().getControl().getModificar() == null) {
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getModificar().getFormularios() == null ) {
				this.getControles().getControl().getModificar().setFormularios(new ArrayList<ControlesFormulariosInfoDTO>());
			}
			
			if ( this.getControles().getControl().getAgregar() == null) {
				this.getControles().getControl().setAgregar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getAgregar().getFormularios() == null ) {
				this.getControles().getControl().getAgregar().setFormularios(new ArrayList<ControlesFormulariosInfoDTO>());
			}
			if ( this.getControles().getControl().getFormularios() == null) {
				this.getControles().getControl().setFormularios(new ArrayList<ControlesFormulariosInfoDTO>());
			}
			
			Integer index = this.getControles().getControl().getFormularios().indexOf(this.getControles().getFormulario());

			if ( this.getControles().getFormulario().getId() == null && index < 0) {
				if( !this.getControles().getControl().getAgregar().getFormularios().contains(this.getControles().getFormulario()) ) {
					ControlesFormulariosInfoDTO formulario = new ControlesFormulariosInfoDTO();
					ObjectUtils.copyValues(this.getControles().getFormulario(), formulario);
					formulario.setOrden(this.getControles().getControl().getFormularios().size()+1);
					/*formulario.setFechaRegistro(DateUtils.getCurrentDate());
					if(formulario.getFechaEmision() != null){
						formulario.setFechaVencimiento(DateUtils.addDays(formulario.getFechaEmision(), 30));
					}*/
					this.log.info("AGREGO FORMULARIO! : {}", formulario);
					this.getControles().getControl().getAgregar().getFormularios().add(formulario);
					this.getControles().getControl().getFormularios().add(formulario);
				}
			} else if(index >= 0) {
				ControlesFormulariosInfoDTO formulario = this.getControles().getControl().getFormularios().get(index);
				this.log.info("MODIFICO FORMULARIO! : {}", this.getControles().getFormulario());
				this.getControles().getFormulario().setOrden(index+1);
				ObjectUtils.copyValues(this.getControles().getFormulario(), formulario);
				formulario.setOrden(index+1);
				/*formulario.setFechaRegistro(DateUtils.getCurrentDate());
				if(formulario.getFechaEmision() != null){
					formulario.setFechaVencimiento(DateUtils.addDays(formulario.getFechaEmision(), 30));
				}*/
				this.log.info("MODIFICO FORMULARIO! : {}", formulario);

				Integer indMod = this.getControles().getControl().getModificar().getFormularios().indexOf(this.getControles().getFormulario());
				if( indMod < 0 ) {
					this.getControles().getControl().getModificar().getFormularios().add(formulario);
				}else{
					ControlesFormulariosInfoDTO forMod = this.getControles().getControl().getModificar().getFormularios().get(indMod);
					ObjectUtils.copyValues(this.getControles().getFormulario(), forMod);
				}
			}
			
			this.getControles().setFormulario(null);
			this.getControles().view().disableAll().enable().formulario();
			this.log.info("FIN!");
			jResponse.setView(View.CONTROL_FORMULARIO);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			} else {
				return jResponse.error(e.getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }
	@RequestMapping(value = "/eventTipoFormulario", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eventTipoFormulario(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROL_FORMULARIO) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("EVENT TIPO FORMULARIO!");
		try {
			ControlesFormulariosInfoDTO formulario = this.getControles().getFormulario();
			formulario.setFormulario(this.helperService.getFormulariosById(formulario.getFormulario().getId()));
			formulario.setControlNaturaleza(new ControlesNaturalezasDTO());
			formulario.setControlVehiculo(new ControlesVehiculosDTO());
			formulario.setControlPersona(new ControlesPersonasDTO());
			this.log.info("TIPO FORMULARIO: {}", this.getControles().getFormulario().getFormulario());
			this.getControles().view().disableAll().enable().formulario();
			this.log.info("FIN!");
			jResponse.setView(View.CONTROL_FORMULARIO_DIALOG);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			} else {
				return jResponse.error(e.getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/guardarControlFormulario", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarControlFormulario(Model model, HttpServletRequest request,
			HttpServletResponse response, @AjaxResponse(View.CONTROL_FORMULARIO) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("\n==============\nGUARDANDO CONTROL_FORMULARIO! \n==============\n");
		try {

			ControlesInfoDTO obj = this.getControles().getControl();

			if ( this.getControles().getControl().getAgregar() == null) {
				this.getControles().getControl().setAgregar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getModificar() == null) {
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getEliminar() == null) {
				this.getControles().getControl().setEliminar(new ControlesDatosDTO());
			}

			this.log.info("Control: {}", obj);
			this.controlesService.saveControlesFormularios(obj);

			this.getControles().setControles(this.controlesService.listControlesRequest(this.getControles().getFiltros()));
			this.getControles().view().disableAll().enable().lista();
			jResponse.setView(View.CONTROLES);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/seguimiento/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse seguimiento(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== Seguimiento CONTROL! {}\n==============\n", ind);
		try {
			
			Integer index = Integer.parseInt(ind);
			ControlesRequestDTO obj = this.getControles().getControles().get(index);
			
			this.log.info("CONTROL: {}", obj);
			this.log.info("ID CONTROL: {}", obj.getIdControl());
			ControlesInfoDTO dto = this.controlesService.showControl(obj.getIdControl());
			List<ControlesseguimientoDTO> notas= this.controlesService.listControlesseguimientoByIdControl(obj.getIdControl());
			if(notas!=null){
				for(ControlesseguimientoDTO cs:notas){
					UsuarioDTO user= administracionService.showUsuario(cs.getIdusuariomodificacion());
					if(user!=null && user.getName()!=null){
						cs.setNombreUsuario(user.getName());
					}
					SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy");
					this.log.info("SimpleDateFormat: {}", sdf.format(cs.getFechacreacion()));
					if(sdf.format(cs.getFechacreacion()).equals(sdf.format(new Date()))){
						cs.setPuedeEditar(true);
					}
				}
			}
		
			this.getControles().setNotas(notas);
			this.getControles().setControl(dto);
			this.getControles().view().disableAll().enable().notas();
			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	@RequestMapping(value = "/agregarNota", method = RequestMethod.POST)
	public @ResponseBody JsonResponse agregarNota(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL_NOTA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("controles - Agregar Nota!");
		this.getControles().setNota(null);
		this.getControles().view().disableAll().enable().notas();
		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	@RequestMapping(value = "/editarNota/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarNota(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL_NOTA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nEditar Nota! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesseguimientoDTO dto = this.getControles().getNotas().get(index);
			if(dto!=null){
				this.getControles().setNota(dto);
			}
			this.getControles().view().disableAll().enable().notas();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	@RequestMapping(value = "/grabarSeguimiento", method = RequestMethod.POST)
	public @ResponseBody JsonResponse grabarSeguimiento(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROL_NOTA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("GUARDAR Control Seguimiento!");
		try{
		Integer index = this.getControles().getNotas().indexOf(this.getControles().getNota());

			if ( (this.getControles().getNota()== null ||this.getControles().getNota().getId() == null) && index < 0) {
				ControlesseguimientoDTO obj=this.getControles().getNota();
				obj.setIdusuario(systemInfo.getIdUser());
				obj.setIdusuariomodificacion(systemInfo.getIdUser());
				obj.setIdcontrol(this.getControles().getControl().getId());
				
				this.log.info("ControlSeguimiento: {}", obj);
				this.controlesService.createControlesseguimiento(obj);
				this.log.info("se creo el control seguimiento {}", obj);
			} else if(index >= 0) {
				ControlesseguimientoDTO obj=this.getControles().getNota();
				obj.setIdusuariomodificacion(systemInfo.getIdUser());
				obj.setIdcontrol(this.getControles().getControl().getId());
				this.log.info("EDITAR ControlSeguimiento: {}", obj);
				this.controlesService.saveControlesseguimiento(obj);
			}
			List<ControlesseguimientoDTO> notas= this.controlesService.listControlesseguimientoByIdControl(this.getControles().getControl().getId());
			if(notas!=null){
				for(ControlesseguimientoDTO cs:notas){
					UsuarioDTO user= administracionService.showUsuario(cs.getIdusuariomodificacion());
					if(user!=null && user.getName()!=null){
						cs.setNombreUsuario(user.getName());
					}
					SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy");
					this.log.info("SimpleDateFormat: {}", sdf.format(cs.getFechacreacion()));
					if(sdf.format(cs.getFechacreacion()).equals(sdf.format(new Date()))){
						cs.setPuedeEditar(true);
					}
				}
			}
			this.getControles().setNotas(notas);
			this.getControles().setNota(null);
			this.getControles().view().disableAll().enable().control();
			this.log.info("FIN!");
			jResponse.setView(View.CONTROL_NOTA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			} else {
				return jResponse.error(e.getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }
	
	@RequestMapping(value = "/eliminarNota/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarNota(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL_NOTA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
			this.log.info("\n==============\nEliminar Nota! {}\n==============\n", ind);
			try {
				Integer index = Integer.parseInt(ind);
				ControlesseguimientoDTO dto = this.getControles().getNotas().get(index);
				if(dto!=null){
					this.controlesService.deleteControlesseguimiento(dto.getId());
					List<ControlesseguimientoDTO> notas= this.controlesService.listControlesseguimientoByIdControl(this.getControles().getControl().getId());
					this.getControles().setNotas(notas);
				}
				this.getControles().view().disableAll().enable().notas();
			} catch (Exception e) {
				this.log.error(e.getMessage(), e);
				if (e.getCause() != null && e.getCause() instanceof RestClientException) {
					return jResponse.error(e.getCause().getMessage());
				}
			}
			return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/controlEscritura/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse controlEscritura(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== Escritura CONTROL! {}\n==============\n", ind);
		try {
			
			Integer index = Integer.parseInt(ind);
			ControlesRequestDTO obj = this.getControles().getControles().get(index);
			
			this.log.info("CONTROL: {}", obj);
			
			this.log.info("ID CONTROL: {}", obj.getIdControl());
			ControlesInfoDTO dto = this.controlesService.showControl(obj.getIdControl());
			if(dto!=null){
				this.log.info("numero:"+dto.getNrocontrol());
			}else{
				this.log.info("controlInfoDTO NULL");
			}
			TabRefDTO estadoAnulado = helperService.getTablaRef(TabRef.ESTADO_ESCRITURA, "020");
			this.log.info("estadoAnulado:"+estadoAnulado);
			ControlesEscriturasDTO ce= new ControlesEscriturasDTO();
			List<ControlesEscriturasDTO> ceList= this.controlesService.getControlesEscriturasByIdControl(dto.getId());
			if(ceList!=null){
				for(ControlesEscriturasDTO c:ceList){
					if(!c.getIdEstadoEscritura().equals(estadoAnulado.getId())){
						ce=c;
						break;
					}
				}
				ceList.remove(ce);
				this.getControles().setOrdenCronologico(ceList);
			}
			if(ce.getEstado()!=null){
				this.getControles().setEstadoPreEdit(ce.getEstado());
			}
			this.getControles().setControl(dto);
			this.getControles().setControlEscritura(ce);
			this.getControles().view().disableAll().enable().escritura();
			
			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/guardarControlEscritura", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarControlEscritura(Model model, HttpServletRequest request,
			HttpServletResponse response, @AjaxResponse(View.CONTROL_ESCRITURA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("\n==============\nGUARDANDO CONTROL_ESCRITURA! \n==============\n");
		try {

			ControlesInfoDTO obj = this.getControles().getControl();
			if(obj!=null){
				this.log.info("numero:"+obj.getNrocontrol());
			}
			if(this.getControles().getControlEscritura().getEstado()!=null){
				this.getControles().getControlEscritura().setIdEstadoEscritura(this.getControles().getControlEscritura().getEstado().getId());
			}
			if(this.getControles().getControlEscritura().getProtocolo()!=null){
				this.getControles().getControlEscritura().setIdProtocolo(this.getControles().getControlEscritura().getProtocolo().getId());
			}

			if ( this.getControles().getControl().getAgregar() == null) {
				this.getControles().getControl().setAgregar(new ControlesDatosDTO());
			}
			if(this.getControles().getControl().getAgregar().getEscrituras()==null){
				this.getControles().getControl().getAgregar().setEscrituras(new ArrayList<ControlesEscriturasDTO>());
			}
			if ( this.getControles().getControl().getModificar() == null) {
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			}
			if(this.getControles().getControl().getModificar().getEscrituras()==null){
				this.getControles().getControl().getModificar().setEscrituras(new ArrayList<ControlesEscriturasDTO>());
			}
			
			if ( this.getControles().getControlEscritura().getId() == null) {
				if( !this.getControles().getControl().getAgregar().getEscrituras().contains(this.getControles().getControlEscritura()) ) {
					ControlesEscriturasDTO escritura = new ControlesEscriturasDTO();
					ObjectUtils.copyValues(this.getControles().getControlEscritura(), escritura);
					
					this.log.info("AGREGO ESCRITURA! : {}", escritura);
					this.getControles().getControl().getAgregar().getEscrituras().add(escritura);
				}
			} else {
				ControlesEscriturasDTO escritura = this.getControles().getControlEscritura();
				this.log.info("MODIFICO ESCRITURA! : {}", this.getControles().getControlEscritura());
				ObjectUtils.copyValues(this.getControles().getControlEscritura(), escritura);
				this.log.info("MODIFICO ESCRITURA! : {}", escritura);
				TabRefDTO estadoAprobado = helperService.getTablaRef(TabRef.ESTADO_ESCRITURA, "010");
				if(this.getControles().getEstadoPreEdit()!=null && this.getControles().getEstadoPreEdit().equals(estadoAprobado)){
					return jResponse.error("NO SE PUEDE MODIFICAR O ANULAR UNA ESCRITURA APROBADA");
				}

				this.getControles().getControl().getModificar().getEscrituras().add(escritura);
			}
//			this.log.info("\n==============\nCONTROL_ESCRITURA! : {}\n==============\n", obj);
			this.controlesService.saveControlesEscrituras(obj);

			this.getControles().setControles(this.controlesService.listControlesRequest(this.getControles().getFiltros()));
			this.getControles().view().disableAll().enable().lista();
			jResponse.setView(View.CONTROLES);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}
	@RequestMapping(value = "/anularEscritura", method = RequestMethod.POST)
	public @ResponseBody JsonResponse anularEscritura(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL_ESCRITURA) JsonResponse jResponse, 
		@ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("controles - Anular escritura!");
		try {
			if(ObjectUtils.isEmpty(this.getControles().getControlEscritura().getMotivoAnulacion()))
				return jResponse.error("Debe ingresar motivo de anulacion");
			TabRefDTO estadoAprobado = helperService.getTablaRef(TabRef.ESTADO_ESCRITURA, "010");
			if(this.getControles().getControlEscritura().getEstado().equals(estadoAprobado)){
				return jResponse.error("NO SE PUEDE MODIFICAR O ANULAR UNA ESCRITURA APROBADA");
			}
			TabRefDTO estadoAnulado = helperService.getTablaRef(TabRef.ESTADO_ESCRITURA, "020");
			TabRefDTO estadoAnuladoControl = helperService.getTablaRef(TabRef.ESTADO_CONTROL, "460");
			this.log.info("ESTADO! : {}", estadoAnulado);
			this.log.info("ESTADOControl! : {}", estadoAnuladoControl);
			if(this.getControles().getControl().getModificar() == null){
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			} 
			if(this.getControles().getControl().getModificar().getEscrituras()==null){
				this.getControles().getControl().getModificar().setEscrituras(new ArrayList<ControlesEscriturasDTO>());
			}
			if(this.getControles().getControlEscritura()==null){
				this.getControles().setOrdenCronologico(new ArrayList<ControlesEscriturasDTO>());;
			}
			ControlesEscriturasDTO escritura = new ControlesEscriturasDTO();
			this.log.info("ESCRITURA! : {}", this.getControles().getControlEscritura());
			ObjectUtils.copyValues(this.getControles().getControlEscritura(), escritura);
			escritura.setEstado(estadoAnulado);
			escritura.setFechaAnulacion(new Date());
			escritura.setIdUsuarioAnulacion(systemInfo.getIdUser());
			this.log.info("MODIFICO ESCRITURA! : {}", escritura);
			this.getControles().getControl().getModificar().getEscrituras().add(escritura);
			this.getControles().getControl().setEstado(estadoAnuladoControl);
			this.controlesService.saveControlesEscrituras(this.getControles().getControl());
			this.getControles().getOrdenCronologico().add(escritura);
			this.getControles().setControlEscritura(new ControlesEscriturasDTO());
			this.getControles().getControl().setModificar(null);
			this.getControles().setControles(this.controlesService.listControlesRequest(this.getControles().getFiltros()));

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/agregarInmueble", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addInmueble(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("controles - Agregar Inmueble!");
		try {
			this.getControles().setInmuebleBuscar(new InmueblesDTO());
			this.getControles().setInmueble(new ControlesInmueblesInfoDTO());
			this.getControles().getInmueble().setMoneda(this.helperService.getMonedasByCodigo("DOL"));
			this.getControles().getControl().setInmuebles(new ArrayList<ControlesInmueblesInfoDTO>());
			this.getControles().view().disableAll().enable().control().inmueble();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}	

	@RequestMapping(value = "/eliminarInmueble/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarInmueble(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO INMUEBLE! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesInmueblesInfoDTO dto = obj.getInmuebles().get(index);
			if( dto == null) {
				return jResponse.error("No existe la inmueble en la lista");
			}
			if ( obj.getEliminar() == null) {
				obj.setEliminar(new ControlesDatosDTO());
			}
			if ( obj.getEliminar().getInmuebles() == null) {
				obj.getEliminar().setInmuebles(new ArrayList<ControlesInmueblesInfoDTO>());
			}
			if ( obj.getModificar() != null && obj.getModificar().getInmuebles() != null) {
				obj.getModificar().getInmuebles().remove(dto);
			}
			if ( obj.getAgregar() != null && obj.getAgregar().getInmuebles() != null) {
				obj.getAgregar().getInmuebles().remove(dto);
			}			
			if ( dto.getId() != null ) {
				obj.getEliminar().getInmuebles().add(dto);
			}
			
			obj.getInmuebles().remove(dto);
			this.getControles().view().disableAll().enable().control();
			jResponse.setView(View.CONTROL_INMUEBLE);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	

	@RequestMapping(value = "/editarInmueble/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarInmueble(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR INMUEBLE! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesInfoDTO obj = this.getControles().getControl();
			ControlesInmueblesInfoDTO dto = obj.getInmuebles().get(index);
			if( dto == null) {
				return jResponse.error("No existe el inmueble en la lista");
			}
			dto.setInmueble(this.inmueblesService.showInmueble(dto.getIdinmueble()));
			this.log.info("INMUEBLE: {}", dto);
			this.getControles().setInmueble(dto);
			this.getControles().view().enable().control().inmueble();
//			jResponse.setView(View.CONTROL_INMUEBLE);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/grabarInmueble", method = RequestMethod.POST)
	public @ResponseBody JsonResponse grabarInmueble(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROL) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {
		this.log.info("GUARDAR INMUEBLE!");
		try {
			
			if ( this.getControles().getControl().getModificar() == null) {
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getModificar().getInmuebles() == null ) {
				this.getControles().getControl().getModificar().setInmuebles(new ArrayList<ControlesInmueblesInfoDTO>());
			}
			
			if ( this.getControles().getControl().getAgregar() == null) {
				this.getControles().getControl().setAgregar(new ControlesDatosDTO());
			}
			if ( this.getControles().getControl().getAgregar().getInmuebles() == null ) {
				this.getControles().getControl().getAgregar().setInmuebles(new ArrayList<ControlesInmueblesInfoDTO>());
			}
			if ( this.getControles().getControl().getInmuebles() == null) {
				this.getControles().getControl().setInmuebles(new ArrayList<ControlesInmueblesInfoDTO>());
			}
			
			Integer index = this.getControles().getControl().getInmuebles().indexOf(this.getControles().getInmueble());

			if ( this.getControles().getInmueble().getId() == null && index < 0) {
				if( !this.getControles().getControl().getAgregar().getInmuebles().contains(this.getControles().getInmueble()) ) {
					ControlesInmueblesInfoDTO inmueble = new ControlesInmueblesInfoDTO();
					ObjectUtils.copyValues(this.getControles().getInmueble(), inmueble);
					inmueble.setOrden(this.getControles().getControl().getInmuebles().size()+1);
					this.log.info("AGREGO INMUEBLE! : {}", inmueble);
					this.getControles().getControl().getAgregar().getInmuebles().add(inmueble);
					this.getControles().getControl().getInmuebles().add(inmueble);
				}
			} else if(index >= 0) {
				ControlesInmueblesInfoDTO inmueble = this.getControles().getControl().getInmuebles().get(index);
				this.log.info("MODIFICO INMUEBLE! : {}", this.getControles().getInmueble());
				this.getControles().getInmueble().setOrden(index+1);
				ObjectUtils.copyValues(this.getControles().getInmueble(), inmueble);
				this.log.info("MODIFICO INMUEBLE! : {}", inmueble);

				Integer indMod = this.getControles().getControl().getModificar().getInmuebles().indexOf(this.getControles().getInmueble());
				if( indMod < 0 ) {
					this.getControles().getControl().getModificar().getInmuebles().add(inmueble);
				}else{
					ControlesInmueblesInfoDTO inmMod = this.getControles().getControl().getModificar().getInmuebles().get(indMod);
					this.getControles().getInmueble().setOrden(index+1);
					ObjectUtils.copyValues(this.getControles().getInmueble(), inmMod);
				}
			}
			
			this.getControles().setInmueble(null);
			this.getControles().view().disableAll().enable().control();
			this.log.info("FIN!");
//			jResponse.setView(View.CONTROL_INMUEBLE);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			} else {
				return jResponse.error(e.getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }
	
	@RequestMapping(value = "/buscarInmuebles", method = RequestMethod.POST)
	public @ResponseBody JsonResponse buscarInmueble(Model model, HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		try {
			InmueblesDTO buscar = this.getControles().getInmuebleBuscar();
			if(ObjectUtils.isEmpty(buscar.getFinca()) && ObjectUtils.isEmpty(buscar.getMatricula())
					&& ObjectUtils.isEmpty(buscar.getCuentacorriente()) && ObjectUtils.isEmpty(buscar.getDistrito())) {
				return jResponse.error("Debe ingresar un parametro para la busqueda");
			}
			
			this.getControles().getInmuebleBuscar().setIdescribano(systemInfo.getIdEscribano());
			List<InmueblesDTO> inmuebles = this.inmueblesService.buscarInmuebles(this.getControles().getInmuebleBuscar());
			this.log.info("inmueble ! : {}", inmuebles);
			this.getControles().setInmuebles(inmuebles);
			jResponse.setView(View.CONTROL_INMUEBLE_DIALOG);
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/departamentoEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse departamemtoEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("INDICADOR DEPARTAMENTO EVENT!");
		try {
			if ( this.getControles().getInmuebleBuscar().getDepartamento() != null) {
				Long idDpto = getControles().getInmuebleBuscar().getDepartamento().getId();
				this.getControles().setDistritos(this.helperService.getDistritos(idDpto));				
			}
			jResponse.setView(View.CONTROL_INMUEBLE_DIALOG);
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/checkInmueble/{id}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse checkInmueble(Model model, HttpServletRequest request, HttpServletResponse response, 
			@PathVariable("id") String id, @AjaxResponse(View.CONTROLES) JsonResponse jResponse, 
			@ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("ID INMUEBLE EVENT! {}", id);
		try {
			Long idInmueble = Long.parseLong(id);
//			InmueblesDTO inmueble = new InmueblesDTO(idInmueble);
			
			for (InmueblesDTO inmueble : this.getControles().getInmuebles()) {
				if(idInmueble.equals(inmueble.getId())){
					inmueble.setMarcar(true);
					this.getControles().getInmueble().setFinca(inmueble != null ? inmueble.getFinca() : null);
					this.getControles().getInmueble().setMatricula(inmueble != null ? inmueble.getMatricula() : null);
					this.getControles().getInmueble().setIdinmueble(inmueble != null ? inmueble.getId() : null);
					this.getControles().getInmueble().setInmueble(inmueble);
				}else{
					inmueble.setMarcar(false);
				}
			}
			 
			jResponse.setView(View.CONTROL_INMUEBLE_DIALOG);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/texto/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse controlTexto(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CONTROLES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== Texto CONTROL! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ControlesRequestDTO obj = this.getControles().getControles().get(index);
			
			this.log.info("ID CONTROL: {}", obj.getIdControl());
			ControlesInfoDTO dto = this.controlesService.showControl(obj.getIdControl());
			this.getControles().setControl(dto);
			try {
				this.getControles().setTexto(this.controlesService.getControlesTextoByIdControl(dto.getId()));
				this.getControles().getTexto().setTemplate(templatesService.showTemplates(this.getControles().getTexto().getIdtemplate()));
			} catch (Exception e) {
				this.log.info("CONTROL NO POSEE ESCRITURA GENERADA");
			}
			
			this.getControles().setTemplates(this.templatesService.listTemplates());
			this.getControles().view().disableAll().enable().texto();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/guardarTexto", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarTexto(Model model, HttpServletRequest request,
			HttpServletResponse response, @AjaxResponse(View.CONTROL_TEXTO) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("\n==============\nGUARDANDO CONTROL TEXTO! \n==============\n");
		try {
			ControlesInfoDTO obj = this.getControles().getControl();

			if ( this.getControles().getControl().getAgregar() == null) {
				this.getControles().getControl().setAgregar(new ControlesDatosDTO());
			}
			if(this.getControles().getControl().getAgregar().getTextos()==null){
				this.getControles().getControl().getAgregar().setTextos(new ArrayList<ControlestextoDTO>());
			}
			if ( this.getControles().getControl().getModificar() == null) {
				this.getControles().getControl().setModificar(new ControlesDatosDTO());
			}
			if(this.getControles().getControl().getModificar().getTextos()==null){
				this.getControles().getControl().getModificar().setTextos(new ArrayList<ControlestextoDTO>());
			}
			
			if ( this.getControles().getTexto().getId() == null) {
				if( !this.getControles().getControl().getAgregar().getTextos().contains(this.getControles().getTexto()) ) {
					ControlestextoDTO texto = new ControlestextoDTO();
					ObjectUtils.copyValues(this.getControles().getTexto(), texto);
					
					this.log.info("AGREGO TEXTO! : {}", texto);
					this.getControles().getControl().getAgregar().getTextos().add(texto);
				}
			} else {
				ControlestextoDTO texto = this.getControles().getTexto();
				this.log.info("MODIFICO TEXTO! : {}", this.getControles().getTexto());
				ObjectUtils.copyValues(this.getControles().getTexto(), texto);
				this.log.info("MODIFICO TEXTO! : {}", texto);
				this.getControles().getControl().getModificar().getTextos().add(texto);
			}
			this.log.info("\n==============\nCONTROL_TEXTO! : {}\n==============\n", obj);
			this.controlesService.saveControlesTexto(obj);

			this.getControles().setControles(this.controlesService.listControlesRequest(this.getControles().getFiltros()));
			this.getControles().view().disableAll().enable().lista();
			jResponse.setView(View.CONTROLES);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/generarTexto", method = RequestMethod.POST)
	public @ResponseBody JsonResponse anularTexto(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CONTROL_TEXTO) JsonResponse jResponse, 
		@ModelAttribute(CONTROLLER_OBJECT_NAME) ControlesControllerObject controles, BindingResult bindingResult) {

		this.log.info("controles - Generar texto!");
		try {
			ControlestextoDTO texto = this.getControles().getTexto();
			if(texto.getTemplate() == null)
				return jResponse.error("Debe ingresar template");
			
			ControlesInfoDTO control = this.getControles().getControl();
			GenerateEscrituraDTO escritura = this.controlesService.generateEscritura(control.getId(), texto.getIdtemplate());
			texto.setTexto(escritura.getDocumento());
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
}	

